<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Auth;
use App\User;
Use App\Post;
Use App\Fan;

class UserController extends Controller
{
  // 
  /* 
      关注
  */
    public function  follow($id){
           
          Fan::create(['fan_id'=>\Auth::id(),'start_id'=>$id]);
          return [
              'error'=>1,
          ];

    }
      /* 
     取消 关注
  */
    public function ufollow($id){
         
          Fan::where(['fan_id'=>\Auth::id(),'start_id'=>$id])->delete();
          return [
              'error'=>1,
          ];

    }

  /* 
        显示个人中心
    */
    //
  public function show($id){
       $user=User::find($id)->post;
       // $user=User::where(compact('id'))->get();
       //home count
       $u=new User;
      
          $user1=User::withCount(['starts','fans'])->find(\Auth::id());

       //start ervery  count
       $arr=Fan::where('fan_id','=',$id)->pluck('start_id');   
       $start=User::whereIn('id',$arr)->withCount(['starts','fans','post'])->get();
       //

      $arr1=Fan::where('start_id','=',$id)->pluck('fan_id');   
       $fan=User::whereIn('id',$arr1)->withCount(['starts','fans','post'])->get();

       
    
      
      return view('user/show',compact('user','fan','start','id','user1'));
  }
    /* 
      个人设置显示
      */
  public function setting(){
      	$users=\Auth::user();

      	return view('/user/setting',compact('users'));
    	
    }
      /* 
    个人设置提交
  */
  public function settingStore(Request $request){
      		$this->validate($request,


      			[
      				'name'=>'required|min:3'
      			]

      		);
      		$name=request('name');
      		$user=\Auth::user();
      		if(request('name')!=\Auth::user()->name){
      				if(User::where('name','=',$name)->count()>0){
      					return \Redirect::back()->withErrors('username no');
      				}
      					$user->name=$name;

      		}
     

     	if ($request->hasFile('avatar')){
        $picture = $request->file('avatar');
        // 文件扩展名
        $extension = $picture->getClientOriginalExtension();
        // 文件名
        $fileName = $picture->getClientOriginalName();
        // 生成新的统一格式的文件名
        $newFileName = md5($fileName . time() . mt_rand(1, 10000)) . '.' . $extension;
        // 图片保存路径
        $savePath = 'avatar/' . $newFileName;
        // Web 访问路径
        $webPath = '/storage/' . $savePath;
       
        $picture->storePubliclyAs('avatar', $newFileName, ['disk' => 'public']);
       
         if(isset($webPath)){
          	 $user->avatar=$webPath;
          }
      	}
        $user->save();
        return back();

       

    }
    	
    	
   	
	
}